import { uploadImage } from "@/actions/base"
import Taro, { showModal } from "@tarojs/taro"
import dayjs from "dayjs"
import { cloneDeep } from 'lodash'
import { useRef, useState } from "react"


export const useImgUpload = (accepts = ['jpg', 'jpeg', 'png', 'image'], params = {}) => {
  const [canvasSize, setCanvasSize] = useState({
    width: 0,
    height: 0
  })
  const [cardInfo, setCardInfo] = useState({ title: '巡检打卡', items: [] })
  const [images, setImages] = useState<{ url: string, isVideo?: boolean }[]>([])
  const nums = useRef(0)
  const beforeRead = (event) => {
    const { file, callback } = event.detail
    let mutiValid = true
    if (Array.isArray(file)) {
      if (file.length > 9) {
        Taro.showToast({ title: '最多选择9张图片' })
        return callback(false)
      }
      file.forEach(i => {
        if (accepts.includes(i.type)) {
          if (i.size > 52428800) {
            mutiValid = false
          }
        } else {
          mutiValid = false
        }
      })
      return callback(mutiValid)
    } else {
      if (accepts.includes(file.type)) {
        if (file.size > 52428800) {
          Taro.showToast({ title: '请选择50M以内的文件', icon: 'none' })
          return callback(false)
        }
        callback(true)
      } else {
        Taro.showToast({ title: '请选择正确的图片或视频格式', icon: 'none' })
        callback(false)
      }
    }


  }
  const geTempImg = () => {
    return new Promise((resolve,reject) => {
      Taro.canvasToTempFilePath({ canvasId: params.watermarkCanvas, fileType: 'jpg' }).then(({ errMsg, tempFilePath }) => {
        if (errMsg === 'canvasToTempFilePath:ok') {
          console.log(10)
          resolve(tempFilePath)
        } else {
          console.log(11)
          reject(errMsg)
        }
      }).catch(e => {
        console.log('添加水印失败：',e)
        reject(e.errMsg)
      })
    })
  }
  const addTimeWatermark = (img: any) => {
    console.log(0,img)
    // setCanvasSize({ width: img.width, height: img.height })
    return new Promise((resolve, reject) => {
      console.log('.........',params.watermarkCanvas)
      const query = Taro.createSelectorQuery()
      query.select(`#${params.watermarkCanvas}`).node(res => {
        console.log(res,'createSelectorQuerycreateSelectorQuery')
        
        const canvas = res.node
        canvas.width = img.width
        canvas.height = img.height
        const context = canvas.getContext('2d')
        context.clearRect(0, 0, img.width, img.height)
        const fileImg = canvas.createImage()
        fileImg.src = img.path || img.url
        fileImg.onload = e => {
          context.drawImage(fileImg, 0, 0, img.width, img.height)
        // const fontSize = 80 * 
        if (params.waterType == 'card') {
          // 设置卡片宽高
          const cardWidth = img.width * 0.3;
          const cardHeight = img.width * 0.15;
          const cardX = 10;
          const cardY = img.height - cardHeight - 10;
          // 绘制卡片背景（蓝色）
          context.fillStyle = 'rgba(0, 0, 0, 0.6)';
          context.fillRect(cardX, cardY, cardWidth, cardHeight);
          console.log(2)
          // 绘制标题背景
          const titleHeight = cardWidth * 0.1;
          context.fillStyle = '#0056b3';
          context.fillRect(cardX, cardY, cardWidth, titleHeight);
          console.log(3)
          // 绘制标题文字
          context.fillStyle = '#FFFFFF';
          context.font = `${cardWidth * 0.06}px Arial`;
          // context.setTextAlign('center')
          context.textAlign = 'center'
          // context.setTextBaseline('middle')
          context.textBaseline = 'middle'
          context.fillText(cardInfo.title, cardX + cardWidth / 2, cardY + titleHeight / 2);
          console.log(4)
          // 绘制内容背景（黑色，透明度0.3）
          context.fillStyle = 'rgba(0, 0, 0, 0.3)';
          context.fillRect(cardX, cardY + titleHeight, cardWidth, cardHeight - titleHeight);
          console.log(5)
          // 绘制内容文字
          context.fillStyle = '#FFFFFF';
          context.font = `${cardWidth*0.04}px Arial`;
          // context.setFontSize(titleHeight * 0.14)
          // context.setTextAlign('left');
          context.textAlign = 'left'
          // context.setTextBaseline('top')
          context.textBaseline = 'top'
  
          console.log(6)
          const lineHeight = cardWidth * 0.1;
          const contentStartX = cardX + 10;
          const contentStartY = cardY + titleHeight + 10;
          console.log(7)
          cardInfo.items.forEach((item, index) => {
            context.fillText(item.text, contentStartX, contentStartY + index * lineHeight);
          });
        } else {
          // context.setFontSize(12 * (img.width / 200))
          context.font = `${12 * (img.width / 200)}px Arial`
          context.setTextBaseline('bottom')
          context.setTextAlign('right')
          context.fillText(dayjs().format('YYYY年MM月DD日 HH:mm:ss'), img.width - 10, img.height - 10)
        }
        console.log(8)
        // context.
        // const canvasImage = canvas.createImage()

        wx.canvasToTempFilePath({ 
          canvasId: params.watermarkCanvas, 
          canvas:canvas,
          fileType: 'jpg',
          success({ errMsg, tempFilePath }) {
            console.log(errMsg,'errrr')
            if (errMsg === 'canvasToTempFilePath:ok') {
              console.log(10)
              resolve(tempFilePath)
            } else {
              console.log(11)
              reject(errMsg)
            }
          },
           complete() {
            console.log('complete')
           },
          fail(res) {
            console.log('添加水印失败：')
            reject(res.errMsg)
          },
         })
        }
        
         console.log('ppppppppp')
        // context.draw(false, () => {
        //   geTempImg().then((result) => resolve(result)).catch(e => {
        //     if (nums.current <5) {
        //       console.log('重试次数：',nums.current)
        //       nums.current+=1
        //       geTempImg()
        //     } else {
        //       Taro.showModal({
        //         title:e
        //       })
        //     }
           
        //   })
        // })
      }).exec()
    
    })


  }
  const handleImageChange = (filesList, action, index) => {

    return new Promise((resolve, reject) => {
      if (action === 'add') {
        const file = filesList[0]
        if (file.type === 'video') {
          if (params.watermark) {
            addTimeWatermark({
              path: file.thumb,
              width: file.width,
              height: file.height
            }).then(tempFilePath => {
              Promise.all([uploadImage(file.url), uploadImage(tempFilePath)]).then(([videoUrl, videoPoster]) => {

                resolve(`${videoUrl}?poster=${encodeURIComponent(videoPoster)}`)
              })
            })
          } else {
            Promise.all([uploadImage(file.url), uploadImage(file.thumb)]).then(([videoUrl, videoPoster]) => {

              resolve(`${videoUrl}?poster=${encodeURIComponent(videoPoster)}`)
            })
          }
          return
        }
        if (params.watermark && params.watermarkCanvas) {
          console.log('添加水印')
          Taro.getImageInfo({
            src: file.url,
            fail(res) {
              Taro.showModal({
                title:'获取图片失败',
                content:res.errMsg
              })
            },
            success(result) {
              console.log('获取图片:', result)
              addTimeWatermark(result).then(tempFilePath => {
                console.log('添加水印完成，图片路径:', tempFilePath)
                console.log('开始上传图片')
                uploadImage(tempFilePath).then((result) => {
                  // '.mp4'.lastIndexOf('.mp4')
                  // Taro.hideLoading()
                  if (result) {
                    console.log('上传图片完成:', result)
                    resolve(result)
                    
                  } else {
                    Taro.showModal({ title: '上传失败',content:result })
                    reject()
                  }

                }).catch((error) => {
                  reject(error);
                  showModal({
                    title: '上传失败',
                    content: error,
                  })
                  // Taro.hideLoading()
                })
              })
            },
          }).catch(e => {
            console.log('添加水印错误：', e)
          })

        } else {
          uploadImage(file.url).then((result) => {
            // '.mp4'.lastIndexOf('.mp4')
            if (result) {

              resolve(result)
            }

          }).catch((error) => {
            reject(error);
            // Taro.hideLoading()
          })
        }

      } else if (action === 'remove') {
        const nextImages = cloneDeep(images)
        const newImages = nextImages.filter((_, i) => i !== index)
        setImages(newImages)
        resolve(true)
      }
    })
  }
  const afterRead = (event) => {
    const { file } = event.detail

    Taro.showLoading({ title: '上传中' })
    if (Array.isArray(file)) {
      Promise.all(file.map(i => handleImageChange([i], 'add', 0))).then((fileResult) => {
        Taro.hideLoading()
        setImages(s => {
          return [...s, ...fileResult.map(src => {
            // @ts-ignore
            const [url, thumb] = (src || '').split('?poster=')
            return ({ url: url.includes('.mp4') ? src : url, isVideo: url.includes('.mp4'), thumb: thumb ? decodeURIComponent(thumb) : url, type: url.includes('.mp4') ? 'video' : 'image' })
          })]
        })
      }).catch((error) => {
        console.log(error, 'error')
        Taro.showToast({ title: '网络异常，请重试' })
        Taro.hideLoading()
      })
      return
    }
    handleImageChange([event.detail.file], 'add', 0).then((src: string) => {
      console.log('上传成功:', src)
      setImages(s => {
        const [url, poster] = (src || '').split('?')
        return [...s, { url: src, isVideo: url.includes('.mp4'), thumb: decodeURIComponent(poster) }]
      })
    }).catch((e) => {
      console.log(e)
      // Taro.hideLoading()
      Taro.showModal({ title: '网络异常，请重试',content:e })
      
    })

  }
  const onDelete = (event) => {
    handleImageChange(null, 'remove', event.detail.index)
  }
  return {
    handleImageChange,
    images,
    setImages,
    beforeRead,
    afterRead,
    onDelete,
    canvasSize,
    setCardInfo
  }
}